"""
轮播图相关序列化器
"""

from rest_framework import serializers
from pecco_site.models import CarouselItem, CarouselTranslation


class CarouselTranslationSerializer(serializers.ModelSerializer):
    """轮播图翻译序列化器"""
    class Meta:
        model = CarouselTranslation
        fields = ['locale', 'title', 'subtitle', 'cta_text']


class CarouselListSerializer(serializers.ModelSerializer):
    """轮播图列表序列化器"""
    translations = CarouselTranslationSerializer(many=True, read_only=True)
    image_url = serializers.SerializerMethodField()

    class Meta:
        model = CarouselItem
        fields = [
            'id', 'image_url', 'link', 'sort_order',
            'is_active', 'created_at', 'updated_at', 'translations'
        ]

    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return None


class CarouselDetailSerializer(serializers.ModelSerializer):
    """轮播图详情序列化器"""
    translations = CarouselTranslationSerializer(many=True, required=False)
    image_url = serializers.SerializerMethodField()
    image = serializers.ImageField(required=False)  # 更新时图片为可选

    class Meta:
        model = CarouselItem
        fields = [
            'id', 'image', 'image_url', 'link', 'sort_order',
            'is_active', 'created_at', 'updated_at', 'translations'
        ]

    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return None

    def create(self, validated_data):
        # Image is required when creating a new carousel item
        if 'image' not in validated_data:
            raise serializers.ValidationError({'image': 'Image is required when creating a carousel item'})
        
        translations_data = validated_data.pop('translations', [])
        carousel = CarouselItem.objects.create(**validated_data)

        for translation_data in translations_data:
            CarouselTranslation.objects.create(item=carousel, **translation_data)

        return carousel

    def update(self, instance, validated_data):
        translations_data = validated_data.pop('translations', None)

        # 更新轮播图基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 更新翻译
        if translations_data is not None:
            # 删除现有翻译
            instance.translations.all().delete()
            # 创建新翻译
            for translation_data in translations_data:
                CarouselTranslation.objects.create(item=instance, **translation_data)

        return instance

